<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <sub-bread></sub-bread>
      <!-- 筛选区 -->
      <sub-filter @filter-change="filterChange"></sub-filter>
      <div class="goods-list">
        <!-- 排序 -->
        <sub-sort @sort-change="sortChange"></sub-sort>
        <!-- 列表 -->
        <ul>
          <li v-for="good in goodList" :key="good.id" >
            <GoodItem :good="good" />
          </li>
        </ul>
        <XtxInfiniteLoading
         :loading="loading"
         :finished="finished"
          @onload="getData"></XtxInfiniteLoading>
      </div>

    </div>
  </div>
</template>

<script setup >
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodItem from './components/good-item.vue'
import { getGoodList } from '@/api/category'
import { useRoute } from 'vue-router'
const loading = ref(false)
const finished = ref(false)
const route = useRoute()
const goodList = ref([])
// 分页参数
let reqParams = {
  page: 1,
  pageSize: 20
}
const getData = () => {
  // 获取数据
  loading.value = true
  // 设置2级分类id
  reqParams.categoryId = route.params.id
  getGoodList(reqParams).then(({ result }) => {
    // 判断result数据是否存在
    if (result.items.length) {
      goodList.value.push(...result.items)
      reqParams.page++
    } else {
      finished.value = true
    }
    loading.value = false
  })
}
// 在更改了二级分类后，清空数据
watch(() => route.params.id, (nVal) => {
  // 判断一下id
  if (nVal && `/category/sub/${nVal}` === route.path) {
    reqParams = {
      page: 1,
      pageSize: 20
    }
    finished.value = false
    // 清空商品列表
    goodList.value = []
  }
})
// 触发排序，重新获取数据
const sortChange = (sortParams) => {
  finished.value = false
  // 保留之前参数并合并新参数
  reqParams = { ...reqParams, ...sortParams }
  reqParams.page = 1
  goodList.value = []
  getData()
}
// 触发筛选，重新获取数据
const filterChange = (filterParams) => {
  // 老套路
  finished.value = false
  // 保留之前参数并合并新参数
  reqParams = { ...reqParams, ...filterParams }
  reqParams.page = 1
  goodList.value = []
  getData()
}
</script>

<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap; // 换行
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
